<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket Chat Client</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
        <fieldset>
            <legend>
                WebSocket服务器
            </legend>
            <!--<input type="text" id="webSocketUrl" value="ws://192.168.1.156:8887" style="width:400px;">-->
            <input type="text" id="webSocketUrl" value="ws://127.0.0.1:8080/websocket/chatClient" style="width:400px;">
            <button onclick="closeWebSocket()">关闭WebSocket连接</button>
            <button onclick="connWebSocket()">连接WebSocket服务器</button>
        </fieldset>
        <fieldset>
            <legend>
                聊天消息
            </legend>
            <div id="chatMessage"></div>
            <hr/>
            用户<input id="user" type="text" value="GACL" style="width:100px;"/>说:
            </label><input id="text" type="text"/>
            <button onclick="sendChatMessage()">发送消息</button>
        </fieldset>
        <fieldset>
            <legend>
                控制台消息
            </legend>
            <fieldset>
                <legend>
                    要发送的消息
                </legend>
                <div id="needSendMessage"></div>
            </fieldset>
            <fieldset>
                <legend>
                    接收到的消息
                </legend>
                <div id="receiveMessage"></div>
            </fieldset>
        </fieldset>
  </body>

  <script type="text/javascript">
      var webSocketClientId;//与WebSocket服务器连接成功后,服务器端会返回一个clientId
      var websocket = null;
      //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常.
      window.onbeforeunload = function () {
          closeWebSocket();
      }

      //将消息显示在网页上
      function showReceiveMessage(innerHTML) {
          document.getElementById('receiveMessage').innerHTML = innerHTML;
      }

      //显示聊天消息
      function showChatMessage(innerHTML){
          document.getElementById('chatMessage').innerHTML += innerHTML+"<br/>";
      }

      //关闭WebSocket连接
      function closeWebSocket() {
          if(websocket != null){
              var paramObj={};
              //需要关闭连接的webSocketClient集合
              paramObj.webSocketClientArr=[];
              var webSocketClient = {};
              webSocketClient.clientId=webSocketClientId;
              paramObj.webSocketClientArr.push(webSocketClient);
              //发送动作消息通知服务器端关闭WebSocket的连接
              sendActionMessage("closeWebSocket",paramObj);
              //连接关闭的回调方法
              websocket.onclose = function (event) {
                  showReceiveMessage(webSocketClientId+"被WebSocket服务器端主动关闭连接了");
              }
              websocket=null;
          }else{
              showReceiveMessage("websocket还没有连接");
          }
      }

      //连接WebSocket
      function connWebSocket() {
          //判断当前浏览器是否支持WebSocket
          if ('WebSocket' in window || 'MozWebSocket' in window) {
              var webSocketUrl = document.getElementById("webSocketUrl").value;
              if(websocket==null){
                  websocket = new WebSocket(webSocketUrl);
                  //连接发生错误的回调方法
                  websocket.onerror = function (event) {
                      showReceiveMessage(event.data);
                  };

                  //连接成功建立的回调方法
                  websocket.onopen = function (event) {

                  }

                  //接收到消息的回调方法
                  websocket.onmessage = function (event) {
                      showReceiveMessage(event.data);
                      var stringWebsocketMessage = JSON.parse(event.data);
                      var messageType = stringWebsocketMessage.messageType;
                      if(messageType=="text"){//文本消息
                          var messageData = stringWebsocketMessage.message;
                          var user = messageData.user;
                          var messageText = messageData.messageText;
                          showChatMessage(user+":"+messageText);
                      }else if(messageType=="sys"){//系统消息
                          //记录服务器端返回的clientId
                          webSocketClientId = stringWebsocketMessage.message.messageData.clientId;
                      }
                  }
              }
          }
          else {
              alert('当前浏览器 Not support websocket')
          }
      }

      /**
       * 显示需要发送的消息
       */
      function showNeedSendMessage(innerHTML){
          document.getElementById('needSendMessage').innerHTML = innerHTML;
      }

      //发送聊天消息
      function sendChatMessage() {
          var user = document.getElementById('user').value;
          var messageText = document.getElementById('text').value;
          //需要发送的消息数据
          var messageData={};
          messageData.user = user;
          messageData.messageText=messageText;
          sendMessage(messageData,"text");
      }

      /**
       *发送操作动作Message
       * action 执行的动作
       * param 参数
       */
      function sendActionMessage(messageText,param){
          //需要发送的消息数据
          var messageData={};
          messageData.messageText=messageText;
          if(param!=undefined){
              messageData.param = param;
          }
          //发送消息
          sendMessage(messageData,"action");
      }

      /**
       * 发送消息
       * @param messageData 消息数据
       * @param messageType 消息类型
       */
      function sendMessage(messageData,messageType) {
          if(websocket!=null){
              //构建需要发送的消息对象
              var stringWebsocketMessage={};
              stringWebsocketMessage.message=messageData;
              stringWebsocketMessage.messageType=messageType;//指明要发送的消息类型，WebSocket服务器端接收到消息后会根据消息类型进行数据推送
              //使用原生的JSON对象的stringify方法将stringWebsocketMessage转成JSON对象并使用WebSocket发送JSON对象
              var message = JSON.stringify(stringWebsocketMessage);
              showNeedSendMessage(message);//测试代码，将要发送的消息打印到页面上显示
              websocket.send(message);//发送消息
          }else{
              alert('请先连接WebSocket服务器')
          }
      }
  </script>
</html>
